package com.example.externalstoreage;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.externalstoreage.utils.FileUtil;
import com.example.externalstoreage.utils.ToastHelper;

import java.io.File;

public class WriteReadActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etInput;
    private TextView tvRead;

    private String fileName = System.currentTimeMillis() + File.separatorChar + ".txt";
    private String filePath = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_write_read);

        etInput = findViewById(R.id.et_input);
        tvRead = findViewById(R.id.tv_read);

        findViewById(R.id.bt_save).setOnClickListener(this);
        findViewById(R.id.bt_read).setOnClickListener(this);
        // 外部存储的私有空间
        // filePath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + File.separatorChar + fileName;
        // 外部存储的公共空间
        // filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + File.separatorChar + fileName;
        // 内部存储私有空间
        filePath = getFilesDir().toString() + File.separatorChar + fileName;

    }


    private void save() {
        String text = etInput.getText().toString();
        FileUtil.saveText(text, filePath);
        ToastHelper.show(this, "保存在" + filePath);
        Log.d("zhoutao", filePath);
    }

    private void read() {
        String text = FileUtil.readText(filePath);
        tvRead.setText(text);
        Log.d("zhoutao", text);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.bt_save) {
            save();
        } else if (id == R.id.bt_read) {
            read();
        }
    }
}